//
//  UserDefaultsTools.m
//  
//
//  Created by  on 16/3/24.
//  Copyright © 2016年 . All rights reserved.
//

//AES 秘钥
#define TOKEN_ENCRY @"AGHDYHSBBS^%$$^GHJJSSKH*&786ghyq"
#import "UserDefaultsTools.h"

@implementation UserDefaultsTools
/**
 *  @author 赵继申, 16-03-24 10:03:27
 *
 *  NSUserDefaults保存
 *
 *  @param value <#value description#>
 *  @param key   <#key description#>
 */
+(void)saveUserDefaultsObject:(id)value forKey:(NSString*)key{
    if (![key isNotEmpty]) {
        return;
    }
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


/**
 得到value

 @param key <#key description#>
 */
+(id)getUserDefaultsForKey:(NSString*)key{
    if (![key isNotEmpty]) {
        return @"";
    }
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

/**
 清除某键
 @param key dey description
 */
+(void)deleteUserDefaultsForKey:(NSString*)key{
    if (![key isNotEmpty]) {
        return;
    }
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault removeObjectForKey:key];
    [userDefault synchronize];
}

/**
 保存token

 @param token <#token description#>
 */
+(void)saveToken:(NSString*)token{
    [self saveUserDefaultsObject:[AESCrypt encrypt:token password:TOKEN_ENCRY] forKey:TOKEN_KEY];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
    NSString *token_timestamp = [NSString stringWithFormat:@"%ld", (long)interval];
    [self saveUserDefaultsObject:token_timestamp forKey:@"TOKEN_TIMESTAMP"];
}

/**
 得到token
 */
+(NSString*)getToken{
    NSString *str = [self getUserDefaultsForKey:TOKEN_KEY];
    if (!str) {
        return nil;
    }
    return [AESCrypt decrypt:str password:TOKEN_ENCRY];
}
/**
 返回token和时间戳,返回值NSDictionary;key分别是 (NSString*)token, (NSNumber*)timestamp
 */
+ (NSDictionary *)getTokenAndTimestamp{
    NSString *token = [UserDefaultsTools getToken];
    if (!token || ![token isNotEmpty]) {
        return nil;
    }
    NSString *timestampStr = [UserDefaultsTools getUserDefaultsForKey:@"TOKEN_TIMESTAMP"];
    if (!timestampStr || ![timestampStr isNotEmpty]) {
        return nil;
    }
    long timestamp = [timestampStr longLongValue];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = token;
    dic[@"timestamp"] = [NSNumber numberWithLong:timestamp];
    return dic;
}

@end
